﻿using System;
using System.Text.RegularExpressions;
using System.Xml;

namespace UwaySoft.EsheetServer.Help.Template
{
    /// <summary>
    /// 模板接口
    /// </summary>
    public abstract class BaseTemplate
    {
        /// <summary>
        /// 检测字符字符串，为空或NULL引发异常
        /// </summary>
        /// <param name="text">要检测字符串</param>
        /// <param name="exceptMessage">异常关联字符窜</param>
        protected void CheckString(string text, string exceptMessage)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentException(exceptMessage);
            }
        }
        /// <summary>
        /// 获取多个节点
        /// </summary>
        /// <param name="xmlDocument"></param>
        /// <param name="xpathExpress">XPath表达式</param>
        /// <returns></returns>
        public static XmlNodeList GetNodes(XmlDocument xmlDocument, string xpathExpress)
        {
            return xmlDocument.SelectNodes(xpathExpress);
        }
        /// <summary>
        /// 获取节点InnerText
        /// </summary>
        /// <param name="xmlDocument"></param>
        /// <param name="xpathExpress">XPath表达式</param>
        /// <returns></returns>
        public static string GetNodeInnerText(XmlDocument xmlDocument, string xpathExpress)
        {
            return GetNodeInnerText(xmlDocument.SelectSingleNode(xpathExpress));
        }
        /// <summary>
        /// 获取节点InnerText
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <param name="xpathExpress">XPath表达式</param>
        /// <returns></returns>
        public static string GetNodeInnerText(XmlNode xmlNode, string xpathExpress)
        {
            return GetNodeInnerText(xmlNode.SelectSingleNode(xpathExpress));
        }
        /// <summary>
        /// 获取节点InnerText
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <returns></returns>
        public static string GetNodeInnerText(XmlNode xmlNode)
        {
            return xmlNode == null ? string.Empty : xmlNode.InnerText;
        }

        /// <summary>
        /// 转义HTML，正则匹配出HTML标签并转换成HTML转义字符
        /// </summary>
        /// <param name="text"></param>
        public string FilterHtml(string text)
        {
            var reg = new Regex("<.+?>", RegexOptions.IgnoreCase);
            var matches = reg.Matches(text);
            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    var htmlValue = (string) match.Value.Clone();
                    htmlValue = htmlValue.Replace("<", "&lt;");
                    htmlValue = htmlValue.Replace(">", "&gt;");
                    text = text.Replace(match.Value, htmlValue);
                }
            }
            return text;
        }
    }
}
